package com.example.sneakerappforme1105.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.sneakerappforme1105.DataProvider;
import com.example.sneakerappforme1105.GoodsDetailActivity;
import com.example.sneakerappforme1105.MainApplication;
import com.example.sneakerappforme1105.R;
import com.example.sneakerappforme1105.SearchActivity;
import com.example.sneakerappforme1105.SpacesDecoration;
import com.example.sneakerappforme1105.ViewModel.CartViewModel;
import com.example.sneakerappforme1105.adapter.RecyclerHomeAdapter;
import com.example.sneakerappforme1105.bean.BackendGoods;
import com.example.sneakerappforme1105.bean.Cart;
import com.example.sneakerappforme1105.bean.CartItem;
import com.example.sneakerappforme1105.bean.Category;
import com.example.sneakerappforme1105.bean.Goods;
import com.example.sneakerappforme1105.constant.NetConst;
import com.example.sneakerappforme1105.dao.CartDao;
import com.example.sneakerappforme1105.dao.CartItemDao;
import com.example.sneakerappforme1105.dao.CategoryDao;
import com.example.sneakerappforme1105.dao.GoodsDao;
import com.example.sneakerappforme1105.database.AppDatabase;
import com.example.sneakerappforme1105.util.RecycleGridDivider;
import com.example.sneakerappforme1105.util.ImageUtil;


import com.example.sneakerappforme1105.util.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class HomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    private String TAG = "HomeFragment";
    protected View mView;
    protected AppCompatActivity mActivity;
    protected GoodsDao goodsDao;
    protected CategoryDao categoryDao;
    protected CartDao cartDao;
    protected CartItemDao cartItemDao;
    private long mUserId; // 登录时传入的用户Id
    private Long mCartId; // 根据 userId 查询 cartId
    private SwipeRefreshLayout srl_fresh;
    private RecyclerView rv_home;
    private RecyclerHomeAdapter adapter;
    private List<Goods> goodsList;
    private List<Category> catList;
    private HashMap<Long, Goods> mGoodsMap = new HashMap<>(); // long 是info.goodsId作为外键
    private CartViewModel cartViewModel;
    private SearchView mSearch;
    private List<BackendGoods> backendGoodsList = new ArrayList<>();

    public HomeFragment(){

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        Log.d(TAG,"HomeFragment启动");
        mActivity = (AppCompatActivity) getActivity();
        mView = inflater.inflate(R.layout.fragment_home, container, false);
        goodsDao = MainApplication.getInstance().getAppDatabase().goodsDao();
        categoryDao = MainApplication.getInstance().getAppDatabase().categoryDao();
        cartDao = MainApplication.getInstance().getAppDatabase().cartDao();
        cartItemDao = MainApplication.getInstance().getAppDatabase().cartItemDao();

        DataProvider dataProvider = (DataProvider) getActivity();   // 用来得到 所挂载活动的成员变量
        if(dataProvider!=null){
            mUserId = dataProvider.getUserId();
            mCartId = dataProvider.getCartId();
        }

        cartViewModel = MainApplication.getInstance().getCartViewModel();   // 直接从mainApplication 中拿到 CartViewModel

        if(mGoodsMap.size()==0){    // 根据商品初始化
            List<Goods> goodsList = goodsDao.queryAllGoods();
            for(Goods g: goodsList){
                mGoodsMap.put(g.getGoodsId(), g);
            }
            cartViewModel.setGoodsMap(mGoodsMap);
            Log.d(TAG,"mGoodsMap大小为"+mGoodsMap.size());
        }

        try {
            initHome(); // 初始化RecyclerView
        } catch (IOException e) {
            e.printStackTrace();
        }


        return mView;
    }


    private void initHome() throws IOException {    // 下一步传入数据

        srl_fresh = mView.findViewById(R.id.srl_refresh);
        srl_fresh.setOnRefreshListener(this);

        // 设置下拉布局的下拉变色资源数组
        srl_fresh.setColorSchemeResources(
                R.color.red, R.color.orange, R.color.green, R.color.blue
        );

        rv_home = mView.findViewById(R.id.rv_home);

        GridLayoutManager manager = new GridLayoutManager(mActivity, 2);

        rv_home.setLayoutManager(manager);  // 设置布局

        Log.d(TAG,"抽取得到的商品信息"+backendGoodsList.size());



        goodsList = goodsDao.queryAllGoods();
        adapter = new RecyclerHomeAdapter(mActivity, goodsList);    // context,数据
        adapter.setOnItemClickListener(new RecyclerHomeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {  // 重写监听方法
                // 点击 进入详情页  卖鞋的详情页
                Goods select = goodsList.get(position); // 点击的商品
                Intent intent = new Intent(mActivity, GoodsDetailActivity.class);    // 跳转到详情页
                intent.putExtra("goodsId", select.getGoodsId());
                intent.putExtra("cartId", mCartId);
                intent.putExtra("userId", mUserId);
                startActivity(intent);
            }
        });

        rv_home.setAdapter(adapter);



        mSearch = mView.findViewById(R.id.my_search);
        mSearch.setOnSearchClickListener(v -> {
            Intent intent = new Intent(mActivity, SearchActivity.class);
            intent.putExtra("userId",mUserId);
            intent.putExtra("cartId",mCartId);
            startActivity(intent);
            // 清除焦点，确保可以再次点击
            mSearch.clearFocus();
        });

        // 获取 SearchView 内部的 EditText
        EditText searchEditText = mSearch.findViewById(androidx.appcompat.R.id.search_src_text);

        // 设置只读
        searchEditText.setFocusable(false);
        searchEditText.setFocusableInTouchMode(false);
        searchEditText.setCursorVisible(false);
        searchEditText.setKeyListener(null);

    }



    private Handler mHandler = new Handler(Looper.myLooper());



    // 刷新任务
    private Runnable mRefresh = new Runnable() {
        @Override
        public void run() {
            srl_fresh.setRefreshing(false);   // 结束下拉刷新布局的刷新动作
            // 更新服装信息列表
            for(int i = goodsList.size()-1, count=0; count<5; count++){
                Goods item = goodsList.get(i);
                goodsList.remove(i);
                goodsList.add(0, item);
            }
            adapter.notifyDataSetChanged(); // 通知适配器列表数据发生变化
            rv_home.scrollToPosition(0); // 让循环试图滚动到第一项所在位置
        }
    };

    @Override
    public void onRefresh() {
        mHandler.postDelayed(mRefresh,2000);
    }


    @Override
    public void onResume() {
        super.onResume();
        SearchView searchView = mView.findViewById(R.id.my_search);
        searchView.clearFocus();
        Log.d(TAG,"HomeFragment重启");
    }


    private void fetchGoods() throws IOException {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(NetConst.HTTP_PREFIX+"goods/all")  // get请求
                .build();


        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                System.out.println("请求图片数据失败!");
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if(response.isSuccessful()){
                    System.out.println("请求图片数据!");
                    String jsonResponse = response.body().string();
                    Gson gson = new Gson();



                    JsonObject jsonObject = gson.fromJson(jsonResponse, JsonObject.class);


                    JsonArray dataArray = jsonObject.getAsJsonArray("data");

                    Type listType = new TypeToken<List<BackendGoods>>() {}.getType();
                    backendGoodsList = gson.fromJson(dataArray, listType);

                    mActivity.runOnUiThread(()->{
                                for (BackendGoods b : backendGoodsList) {
                                    String imagePath = null;
                                    try {
                                        String base64ImageData = b.getImageData();// String
                                        // 解码 Base64 字符串为字节数组
                                        byte[] imageBytes = Base64.decode(base64ImageData, Base64.DEFAULT);  // 使用 Base64 解码
                                        imagePath = ImageUtil.saveImageToLocal(imageBytes, "goods_" + b.getGoodsId() + ".png", String.valueOf(mActivity.getExternalFilesDir("")));
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    Goods goods = new Goods();
                                    goods.setGoodsId(b.getGoodsId());
                                    goods.setCategoryId(b.getCategory().getCategoryId());
                                    goods.setName(b.getName());
                                    goods.setDesc(b.getDes());
                                    goods.setPrice(b.getPrice());
                                    goods.setPicPath(imagePath);
                                    goods.setCapcity(b.getCapcity());
                                    goods.setStatus(b.getStatus());

                                    goodsDao.insertOneGoods(goods);

                                }
                                adapter.notifyDataSetChanged();
                    });





                }
            }
        });
    }

}
